package com.example.back.service.impl;

import cn.hutool.core.convert.Convert;
import com.example.back.dto.MenuTree;
import com.example.back.dto.req.RoleReq;
import com.example.back.dto.req.RolesCommitSaveReq;
import com.example.back.dto.resp.RolesResp;
import com.example.back.jpa.SysModuleRepository;
import com.example.back.jpa.SysRoleModulesRepository;
import com.example.back.jpa.SysRolesRepository;
import com.example.back.mapper.SysRolesMapper;
import com.example.back.service.SysRolesService;
import com.example.back.utils.LevelUtils;
import com.example.common.entity.*;
import com.example.common.support.ApiException;
import com.example.common.utils.CheckUtils;
import com.example.common.utils.IdUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.javers.spring.annotation.JaversAuditable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 角色管理
 */
@Service
public class SysRolesServiceImpl implements SysRolesService {
    @Resource
    private SysRolesMapper sysRolesMapper;
    @Resource
    private SysRolesRepository sysRolesRepository;
    @Resource
    private SysRoleModulesRepository sysRoleModulesRepository;

    @Resource
    private SysModuleRepository sysModuleRepository;
    /**
     * 获取角色列表
     * @param req
     * @return
     */
    @Override
    public PageInfo<RolesResp> list(RoleReq req) {

        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        //分页页码，默认1页
        int pageNumber = null == req.getPage() ? 1 : req.getPage();
        //分页条数，默认10条
        int pageSize = null == req.getLimit() ? 10 : req.getLimit();
        //角色名称
        String name = req.getName();
        return PageHelper
                .startPage(pageNumber, pageSize)
                .doSelectPageInfo(() -> sysRolesMapper.findRolesByName(name));
    }

    /**
     * 模块管理
     * @param req
     * @return
     */
    @Override
    public List<MenuTree> modulelist(RoleReq req) {

        List<Module> ModuleList = new ArrayList<>();
        List<Module> sysModuleList = sysModuleRepository.findAll();
        for (Module module : sysModuleList) {
            List<RoleModules> roleModules = sysRoleModulesRepository.findByRid(req.getID());
            for (RoleModules roleModules1 : roleModules) {

                if (module.getId().equals(roleModules1.getMid())) {
                    module.setCheckType(true);
                }
            }
            ModuleList.addAll(sysModuleList);
        }
        return LevelUtils.level(ModuleList, false);
    }

    /**
     * 新增和修改角色管理权限
     * @param req
     * @return
     */
    @Override
    @JaversAuditable
    @Transactional(rollbackFor = Exception.class)
    public Object commitSave(RolesCommitSaveReq req) {

        String[] split = req.getIDS().split(",");
        List<RoleModules> list = new ArrayList<>();
        if(split == null){
            throw new ApiException(1, "模块ID不存在");
        }

        if(req.getID()==0){
            Roles  obj = new Roles();
            obj.setId(IdUtils.generateId());
            obj.setName(req.getName());
            obj.setRemark(req.getName());
            obj.setCreateTime(new Date());
            for (String id : split) {
                Long myInt = Convert.toLong(id);
                RoleModules item = new RoleModules();
                item.setId(IdUtils.generateId());
                item.setRid(obj.getId());
                item.setMid(myInt);
                list.add(item);
            }

            if(list.size()>0){
                sysRoleModulesRepository.saveAll(list);
            }
            sysRolesRepository.save(obj);
        }else {

            List<RoleModules> roleModules = sysRoleModulesRepository.findByRid(req.getID());

            Roles objs = sysRolesRepository.findById(req.getID()).orElse(null);
            if(objs==null){
                throw new ApiException(1, "错误的请求参数");
            }
            if(roleModules.size()>0){
                sysRoleModulesRepository.deleteAll(roleModules);
            }

            for (String ids : split) {
                Long myInt = Convert.toLong(ids);
                RoleModules item = new RoleModules();
                item.setId(IdUtils.generateId());
                item.setRid(objs.getId());
                item.setMid(myInt);
                list.add(item);
            }

            objs.setName(req.getName());
            sysRolesRepository.save(objs);

            if(list.size()>0){
                sysRoleModulesRepository.saveAll(list);
            }

        }
        return null;
    }


    /**
     * 角色管理删除
     * @param req
     * @return
     */
    @Override
    @JaversAuditable
    @Transactional(rollbackFor = Exception.class)

    public Object commitDel(RoleReq req) {

        Roles obj = sysRolesRepository.findById(req.getID()).orElse(null);
        List<RoleModules> roleModules = sysRoleModulesRepository.findByRid(req.getID());

        sysRolesRepository.deleteById(obj.getId());
        sysRoleModulesRepository.deleteAll(roleModules);
        return null;
    }
}
